package whitelistdao

import (
	"vpn-management-server/logger"
	"vpn-management-server/src/dao"
	"vpn-management-server/src/model/whitelistmodel"
)

func AddWhiteList(ugid int, whitelist []*Whitelistmodel.WhiteItem) (int, error) {
	tx, _ := dao.GMysqlDB.Conn.Begin()
	for i, Item := range whitelist {
		sqlStr := "INSERT INTO white_list(phone,real_name,icard,invitation,ug_id) value(?,?,?,?,?)"
		_, err := tx.Exec(sqlStr, Item.Phone, Item.RealName, Item.ICard, Item.Invitation, ugid)
		if err != nil {
			logger.Logger.Error(err)
			tx.Rollback()
			return i, err
		}
	}
	return -1, tx.Commit()
}

func HasPhones(phoneList []string) (int, bool) {
	var whiteItem Whitelistmodel.WhiteItem
	sqlStr := "SELECT * FROM white_list where phone = ?"
	for i, phone := range phoneList {
		if err := dao.GMysqlDB.Conn.Get(&whiteItem, sqlStr, phone); err == nil {
			return i, true
		} else {
			logger.Logger.Debug(err)
		}
	}
	return -1, false
}

func DeleteWhiteList(IDs []int) (int, error) {
	tx, _ := dao.GMysqlDB.Conn.Begin()
	for i, id := range IDs {
		sqlStr := "DELETE FROM white_list where id = ?"
		_, err := tx.Exec(sqlStr, id)
		if err != nil {
			logger.Logger.Error(err)
			tx.Rollback()
			return i, err
		}
	}
	return -1, tx.Commit()
}

func GetWhiteListByPage(pageNo, pageSize, ugid int) []*Whitelistmodel.WhiteItem {
	start := (pageNo - 1) * pageSize
	var whiteList []*Whitelistmodel.WhiteItem
	sqlStr := "SELECT * FROM white_list where ug_id = ? LIMIT ?,?"
	err := dao.GMysqlDB.Conn.Select(&whiteList, sqlStr, ugid, start, pageSize)
	if err != nil {
		logger.Logger.Error(err)
		return nil
	}
	return whiteList
}

func GetWhiteListCountByUGroupID(ugid int) int {
	var count int
	sqlStr := "SELECT COUNT(*) FROM white_list WHERE ug_id = ?"
	err := dao.GMysqlDB.Conn.Get(&count, sqlStr, ugid)
	if err != nil {
		logger.Logger.Error(err)
		return -1
	}
	return count
}

func GetAllWhiteListCount() int {
	var count int
	sqlStr := "SELECT COUNT(*) FROM white_list"
	err := dao.GMysqlDB.Conn.Get(&count, sqlStr)
	if err != nil {
		logger.Logger.Error(err)
		return -1
	}
	return count
}

func GetWhiteItemByPhone(phone string) *Whitelistmodel.WhiteItem {
	var whiteItem Whitelistmodel.WhiteItem
	sqlStr := "SELECT * FROM white_list where phone = ?"
	err := dao.GMysqlDB.Conn.Get(&whiteItem, sqlStr, phone)
	if err != nil {
		logger.Logger.Debug(err)
		return nil
	}
	return &whiteItem
}

func GetUGroupIDByPhone(phone string) int {
	var id int
	sqlStr := "SELECT ug_id FROM white_list where phone = ?"
	err := dao.GMysqlDB.Conn.Get(&id, sqlStr, phone)
	if err != nil {
		logger.Logger.Error(err)
		return -1
	}
	return id
}
